/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.proyectoTiberio.utility;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.proyectoTiberio.entity.CityEntity;
import com.proyectoTiberio.entity.PollEntity;
import java.util.ArrayList;

/**
 *
 * @author chema
 */
public class GsonUtility {
    
    public static ArrayList<PollEntity> parsearPoll (Gson gson, String json)
    {
        ArrayList<PollEntity> pollArray = new  ArrayList<PollEntity>();
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(json).getAsJsonArray();
        
        for(JsonElement elem : jsonArray)
        {
            try{
                pollArray.add(gson.fromJson(elem, PollEntity.class));
            }
            catch(Throwable t){
                System.out.println("el elemteo de tipo " +elem.toString()+"no se puede parsear");
                System.out.println(t);
            }
            
        }
        
        return pollArray;
        
       
    }

    public static String toJson(ArrayList<String> args, String sesion) {
       
         String datosjson = "{\"session\":\"" + sesion;
        
        if(args!=null)
        {
            datosjson+=",";
            for (int i = 0; i < (args.size()-2); i = i + 2)
            {
                if(!esEntero(args.get(i)))
                    datosjson += datosjson +"\""+args.get(i) +"\":"
                                +"\""+args.get(i) +"\",";
                else
                    datosjson += datosjson +"\""+args.get(i) +"\":"
                                +args.get(i)+",";
            }
            
             if(!esEntero(args.get(args.size()-2)))

                datosjson += datosjson +"\""+args.get(args.size()-2) +"\":"
                                 +"\""+args.get(args.size()-1) +"\"";
             else
                
                 datosjson += datosjson +"\""+args.get(args.size()-2) +"\":"
                                 +args.get(args.size()-1);
            
        }
        
        
        datosjson+=  "\"}";
        
        return datosjson;
    }
    
    
    private static boolean esEntero(String arg ) {
        
        //sequenceid\":" + secuentId++ + ",\"requestid\":" + requestId++ + ",\"reques
        return ("sequenceid".equals(arg) || "requestid".equals(arg) || "version".equals(arg));
    }
    
}
